# -*- coding: UTF-8 -*-
import sys,os
import time
import ConfigParser
import MySQLdb


def read_config_str(config_file_path,field,key):
    cf=ConfigParser.ConfigParser()
    try:
        cf.read(config_file_path)
        result=cf.get(field,key)
    except:
        sys.exit(1)
    return result

def read_config_int(config_file_path,field,key):
    cf=ConfigParser.ConfigParser()
    try:
        cf.read(config_file_path)
        result=cf.getint(field,key)
    except:
        sys.exit(1)
    return result

def db_test():
    # 打开数据库连接
    i=1
    db_ip = read_config_str("config.ini", "dbconf", "db_ip")
    db_port = read_config_str("config.ini", "dbconf", "db_port")
    db_user = read_config_str("config.ini", "dbconf", "db_user")
    db_password = read_config_str("config.ini", "dbconf", "db_password")
    db_name = read_config_str("config.ini", "dbconf", "db_name")
    name = read_config_str("config.ini", "baseconf", "name")
    delay_time=read_config_int("config.ini", "baseconf", "delay_time")
    cycle_time=read_config_int("config.ini", "baseconf", "cycle_time")
    db_read_cycle=read_config_int("config.ini", "dbconf", "db_read_cycle")
    tmp='taskkill /f /im '+name
    #print db_ip, db_port, db_user, db_password
    while True:
        db = MySQLdb.connect(db_ip,db_user,db_password ,db_name)
        # 使用cursor()方法获取操作游标
        cursor = db.cursor()
        # 使用execute方法执行SQL语句
        cursor.execute("SELECT SHTIME FROM snhis ORDER BY SHTime DESC LIMIT 1")
        # 使用 fetchone() 方法获取一条数据库。
        data_tmp = cursor.fetchone()
        # 转换成时间数组
        timeArray = time.strptime(str(data_tmp[0]), "%Y-%m-%d %H:%M:%S")
        # 转换成时间戳
        timestamp = time.mktime(timeArray)
        # 关闭数据库连接
        db.close()
        print "MySQL datatime:",data_tmp[0]
        print "system datatime:",time.strftime("%Y-%m-%d %X", time.localtime())
        #print time.time()

        if((time.time()-timestamp)>cycle_time):
            os.system(tmp)
            file=open('log.txt','a+')
            lines = file.readlines()  # 读取所有行
            if(len(lines)==0):
                i = 1
            else:
                first_line = lines[0]  # 取第一行
                last_line = lines[-1]  # 取最后一行
                if (last_line.index(',')):
                    i=int(last_line.split(',')[0])+1#get index
            now=time.strftime("%Y-%m-%d %X", time.localtime())
            file_tmp=str(i)+','+now+' close '+name+'\n'
            file.write(file_tmp)
            file.close()
            print  file_tmp
            time.sleep(delay_time)
        time.sleep(db_read_cycle)




if __name__ == '__main__':

    db_test()
